<template>
  <div class="car">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <!-- 车辆列表 -->
    <div class="carList" v-if="fileList && fileList.length">
      <div class="carItem flex" v-for="(item, index) in fileList" :key="index">
        <div class="file_lt">
          <i class="iconfont icon-file"></i>
          {{ item.ATTNAME }}
        </div>
        <i v-if="!item.downTxt" @click="downloadFile(item)" class="iconfont icon-download"></i>
        <span class="downTxt" v-else>{{ item.downTxt }}</span>
      </div>
    </div>
    <div class="carList" v-if="newFiles && newFiles.length">
      <div class="carItem flex" v-for="(item, index) in newFiles" :key="index">
        <div class="file_lt">
          <i class="iconfont icon-file"></i>
          {{ item.name }}
        </div>
        <van-icon name="clear" color="#cecece" size="20px" @click="delData(item, index)" />
      </div>
    </div>
    <van-empty class="noContent" description="暂无数据" v-if="fileList.length == 0 && newFiles.length == 0" />
    <div class="footer">
      <div class="footerBtn flex">
        <div class="btnType selBtn">
          选择文件
          <input type="file" @change="getFiles" multiple="multiple" class="file_ipt" />
        </div>
        <div class="btnType uploadBtn" @click="referFile" :class="{ disable_btn: newFiles.length == 0 }">立即上传</div>
      </div>
    </div>
  </div>
</template>

<script>
import { Empty, Toast, Dialog } from "vant";
const base_url = process.env.BASE_API;
import commonApi from "@/api/commonApi";
import commJs from "@/assets/js/commJs";

export default {
  name: "fileMange",
  components: {
    Empty,
    Dialog
  },
  data() {
    return {
      fileList: [],
      newFiles: [],
      fileData: new FormData(),
      billId: ""
    };
  },

  mounted() {
    if (this.$route.query && this.$route.query.billId) {
      this.billId = this.$route.query.billId;
      this.getFileList(this.$route.query.billId);
    }
    console.log("base_url", base_url);
  },
  methods: {
    getFileList(billId) {
      commonApi.getFileList({ billId }).then(res => {
        console.log(res);
        res.records &&
          res.records.map(item => {
            item.downTxt = "";
            item.progress = null;
          });
        this.fileList = res.records;

        console.log(this.newFiles);
      });
    },
    dataURLtoFile(dataurl, filename) {
      // base64转file
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime
      });
    },
    canvasDataURL(path, objCompressed, callback) {
      // 压缩图片
      var img = new Image();
      var _this = this;
      img.src = path;
      img.onload = function() {
        var that = this;
        // 默认压缩后图片规格
        var quality = 0.5;
        var w = that.width;
        var h = that.height;
        var scale = w / h;

        // 判断图片是竖的还是横的
        if (w < h) {
          w = h;
          _this.trans = true;
        }

        // 实际要求
        w = objCompressed.width || w;
        h = objCompressed.width / scale || w / scale;

        if (
          objCompressed.quality &&
          objCompressed.quality > 0 &&
          objCompressed.quality <= 1
        ) {
          quality = objCompressed.quality;
        }

        // 生成canvas
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);

        var base64 = canvas.toDataURL("image/jpeg", quality);
        // 回调函数返回base64的值
        callback(base64);
      };
    },
    // 上传文件处理
    getFiles(e, index, j) {
      const files = e.target.files;
      const _this = this;
      console.log(files);
      if (files.length >= 10) {
        Toast("一次最多只能上传10个文件");
        return false;
      }
      for (var i = 0; i < files.length; i++) {
        const data = {
          file: files[i],
          name: files[i].name.slice(0, files[i].name.lastIndexOf(".")),
          suffix: files[i].name.slice(files[i].name.lastIndexOf("."))
        };
        _this.newFiles.unshift(data);
        console.log(_this.newFiles);
      }
    },
    delData(data, index) {
      data.name = "";
      this.newFiles.splice(index, 1);
    },
    // 提交附件
    referFile() {
      const _this = this;
      const files = _this.newFiles;

      if (_this.newFiles.length == 0) {
        return false;
      }

      for (let i = 0; i < files.length; i++) {
        const url = "";
        if (files[i].name == "") {
          Toast("文件名不能为空");
          return false;
        }
        if (files[i].file.type.split("/")[1] != "image") {
          // 非图片
          if (files[i].file.size > 5242880) {
            Toast("文件不得大于5M");
            return false;
          }
          _this.fileData.append(
            "files",
            files[i].file,
            files[i].name + files[i].suffix
          );
        } else {
          var reader = new FileReader();
          reader.readAsDataURL(files[i].file);
          reader.onload = function(e) {
            _this.canvasDataURL(
              this.result,
              {
                quality: 0.2
              },
              function(base64Codes) {
                var file = _this.dataURLtoFile(base64Codes, files[i].name);

                _this.fileData.append("files", file, files[i].name); // 文件对象
              }
            );
          };
        }
      }
      Dialog.confirm({
        title: "确定上传？",
        message: `确定上传${_this.newFiles.length}个文件？`
      })
        .then(() => {
          console.log(12321231);
          _this.fileData.append("billType", "CarInfo");
          _this.fileData.append("billId", encodeURI(_this.billId));
          console.info(_this.fileData);
          commonApi.uploadFiles(_this.fileData).then(res => {
            if (res.data.errcode == 0) {
              _this.fileData.delete("files");
              _this.fileData.delete("billType");
              _this.fileData.delete("billId");
              _this.newFiles = [];
              _this.getlistFiles();
            }
          });
        })
        .catch(() => {
          _this.fileData.delete("files");
          _this.fileData.delete("billType");
          _this.fileData.delete("billId");
        });
    },
    // 下载文件
    downloadFile(data) {
      console.log(data);
      const formData = {
        attachId: encodeURI(data.ATTID),
        attachName: data.ATTNAME
      };
      const _this = this;
      var link = document.createElement("a");

      if (data.fileName && commJs.testPlat() == 1) {
        link.href = `${base_url}/download/${data.fileName}`;
        link.download = data.fileName;
        link.click();
        URL.revokeObjectURL(link.href);
        return false;
      }
      // if (this.lock) {
      //   return false
      // }

      data.progress = data.progress | 0;
      if (data.progress == 100 && commJs.testPlat() == 0) {
        Toast("该文件已下载，请勿重复下载！");
        return false;
      } else {
        data.downTxt = "已下载";
      }
      this.lock = true;
      var config = {
        onUploadProgress: progressEvent => {
          var complete =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          data.progress = complete;
          if (data.progress == 100) {
            this.lock = false;
          }
        }
      };
      // commonApi.downloadFile({ ...formData, ...config }).then((res) => {
      const src = `${base_url}/proxy/cam/file/download?attachId=${formData.attachId}&attachName=${formData.attachName}`;
      var link = document.createElement("a");
      data.fileName = formData.attachName;
      link.href = src;
      // link.download = res.data.data
      link.click();
      URL.revokeObjectURL(link.href);
      // })
    }
  }
};
</script>

<style lang="less" scoped>
body {
}
.flex {
  display: flex;
  align-items: center;
}
.car {
  padding-bottom: 80px;
}

.carList {
  background: #fff;

  .carItem {
    background: #fff;
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
    justify-content: space-between;
    .file_lt {
      font-size: 13px;
      color: #161616;
    }

    .icon-file {
      color: #999;
      margin-right: 5px;
      position: relative;
      top: 1px;
    }
    .icon-download {
      font-size: 25px;
      color: #409eff;
    }
    .vin {
      color: #666;
      font-size: 14px;
    }
    &:last-child {
      border: none;
    }
  }
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 99;
  width: 100%;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  .footerBtn {
    margin: 15px;
    justify-content: space-between;
    .btnType {
      border-radius: 5px;
      color: #fff;
      text-align: center;
      width: 165px;
      padding: 15px 0;
      font-size: 15px;
      position: relative;
    }
    .selBtn {
      background: #409eff;
      position: relative;
    }
    .uploadBtn {
      background: #409eff;
    }
    .disable_btn {
      background: #ccc;
    }
  }
}

.file_ipt {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  opacity: 0;
  width: 100%;
  display: block;
}
.downTxt {
  font-size: 12px;
  color: #666;
}
</style>
